<!-- 原始事件 日志 -->
<template>
    <div class="user_main">
        <div class="safelist-search-container mb-16">
            <a-row class="search-row">
                <a-col class="mr-8">
                    <a-input style="width: 200px;" v-model:value="state.searchData.likeVehiclePlateLicense" placeholder="输入车牌" />
                </a-col>
                <a-col class="mr-8">
                    <a-select v-model:value="state.searchData.alarmCode" class="mr-8" style="width: 150px;"
                        placeholder="全部报警类型" optionFilterProp="label">
                        <a-select-option v-for="item in getEnumOptions('alarmEvent')" :value="item.value" :key="item.value">{{ item.label }}</a-select-option>
                        
                    </a-select>
                </a-col>
                <a-col class="mr-8">
                    <a-range-picker v-model:value="state.searchData.date" 
                    :allowClear="false"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                     @change="changeDate" />
                </a-col>
                <a-col>
                    <a-button type="primary" class="mr-8" @click="handleSearch">搜索</a-button>
                    <a-button type="primary" class="mr-8" ghost @click="handleEmpty">重置</a-button>
                    <a-button type="primary" ghost @click="handleBatchExport">批量导出</a-button>
                </a-col>
            </a-row>
        </div>
        <div class="safelist-table-container">
            <a-table 
                :columns="tableProps.columns" 
                :data-source="tableProps.dataSource"
                :pagination="tableProps.pagination" 
                :scroll="{ y: 'calc(100vh - 200px)' }"
                :row-selection=" tableProps.rowSelection"
                row-key="id">
                <template #bodyCell="{ column, record }">
                    <!-- 事件等级 -->
                    <div v-if="column.dataIndex === 'riskLevel'">
                        <a-tag :color="getAlarmLevelColor(record.riskLevel)">
                            {{ getEnumValue('eventLevel',record.riskLevel) }}
                        </a-tag>
                    </div>
                    <div v-if="column.dataIndex === 'alarmCode'">
                        {{ getEnumValue('alarmEvent',record.alarmCode) }}
                    </div>
                    <!-- 处理状态 -->
                    <div v-if="column.dataIndex === 'isActive'">
                        <a-tag :color="record.isActive ? 'green' : 'red'">
                            {{ record.isActive ? '启用' : '禁用' }}
                        </a-tag>
                    </div>
                    
                    <!-- 操作 -->
                    <div v-if="column.dataIndex === 'action'" class="action_box">
                        <span @click="viewDetail(record)">查看</span>
                        <!-- <span v-if="record.processStatus === '未处理'" @click="handleAlarm(record)" class="process_btn">处理</span> -->
                        <span @click="deleteAlarm(record)" class="delete_btn">删除</span>
                    </div>
                </template>
            </a-table>
        </div>

        <!-- 详情弹窗 -->
        <a-modal 
            v-model:open="state.detailVisible" 
            title="事件详情" 
            width="800px"
            :footer="null"
            @cancel="closeDetail">
            <div class="detail-content">
                <a-descriptions :column="2" bordered>
                    <a-descriptions-item label="事件ID">{{ state.detailData.id }}</a-descriptions-item>
                    <a-descriptions-item label="车牌号">{{ state.detailData.vehiclePlateLicense }}</a-descriptions-item>
                    <a-descriptions-item label="事件地址">{{ state.detailData.address }}</a-descriptions-item>
                    <a-descriptions-item label="报警代码">{{ state.detailData.alarmCode }}</a-descriptions-item>
                    <a-descriptions-item label="事件等级">
                        <a-tag :color="getAlarmLevelColor(state.detailData.riskLevel)">
                            {{ state.detailData.riskLevel }}
                        </a-tag>
                    </a-descriptions-item>
                    <a-descriptions-item label="区域类型">{{ state.detailData.riskLevel }}</a-descriptions-item>
                    <a-descriptions-item label="经度">{{ state.detailData.lo }}</a-descriptions-item>
                    <a-descriptions-item label="纬度">{{ state.detailData.la }}</a-descriptions-item>
                    <a-descriptions-item label="车企名称">{{ state.detailData.manufacturerName }}</a-descriptions-item>
                    <a-descriptions-item label="车企ID">{{ state.detailData.manufacturerId }}</a-descriptions-item>
                    <a-descriptions-item label="运营商名称">{{ state.detailData.operatorName }}</a-descriptions-item>
                    <a-descriptions-item label="运营商ID">{{ state.detailData.operatorId }}</a-descriptions-item>
                    <a-descriptions-item label="负责人姓名">{{ state.detailData.directorName }}</a-descriptions-item>
                    <a-descriptions-item label="负责人电话">{{ state.detailData.directorPhone }}</a-descriptions-item>
                    <a-descriptions-item label="车辆ID">{{ state.detailData.vehicleId }}</a-descriptions-item>
                    <a-descriptions-item label="状态">
                        <a-tag :color="state.detailData.isActive ? 'green' : 'red'">
                            {{ state.detailData.isActive ? '启用' : '禁用' }}
                        </a-tag>
                    </a-descriptions-item>
                    <a-descriptions-item label="创建时间">{{ formatDateTime(state.detailData.createTime) }}</a-descriptions-item>
                    <a-descriptions-item label="创建用户ID">{{ state.detailData.createUserId }}</a-descriptions-item>
                    <a-descriptions-item label="更新时间">{{ formatDateTime(state.detailData.updateTime) }}</a-descriptions-item>
                    <a-descriptions-item label="更新用户ID">{{ state.detailData.updateUserId }}</a-descriptions-item>
                </a-descriptions>
            </div>
        </a-modal>

        <!-- 处理报警弹窗 -->
        <!-- <a-modal v-model:open="state.processVisible" title="处理报警" @ok="confirmProcess" @cancel="cancelProcess">
            <a-form :model="state.processForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                <a-form-item label="处理意见">
                    <a-textarea v-model:value="state.processForm.opinion" :rows="4" placeholder="请输入处理意见" />
                </a-form-item>
            </a-form>
        </a-modal> -->
    </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { message } from "ant-design-vue";
import dayjs from 'dayjs';
import { bizEventQueryPage ,bizEventDetail,bizEventExportByIdList,bizEventDelete} from "@/service/nmcApi"
// import { bizEventQueryPage ,bizEventDetail} from "@/service/nmcApi"
import { getEnumOptions,getEnumValue } from '@/utils/enum'
import { downloadExcelByBlob, downloadZipByBlob,deleteConfirmModal } from "@/utils";

const tableProps = ref({
    columns: [
        {
            title: '事件类型',
            dataIndex: 'alarmCode',
            width: 120
        },
        {
            title: '事件等级',
            dataIndex: 'riskLevel',
            width: 100
        },
        {
            title: '事件地点',
            dataIndex: 'address',
            width: 200
        },

        {
            title: '车牌',
            dataIndex: 'vehiclePlateLicense',
            width: 100
        },
        {
            title: '车企',
            dataIndex: 'manufacturerName',
            width: 180
        },
        {
            title: '运营公司',
            dataIndex: 'operatorName',
            width: 100
        },
        {
            title: '负责人电话',
            dataIndex: 'directorPhone',
            width: 120
        },
        {
            title: '负责人姓名',
            dataIndex: 'directorName',
            width: 100
        },
        {
            title: '发生时间',
            dataIndex: 'createTime',
            width: 100
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 150,
            fixed: 'right'
        }
    ],
    dataSource: [], //列表数据
    pagination: {
        current: 1,//当前页数
        pageSize: 10,//每页条数
        total: 0,
        showSizeChanger: true,
        showTotal: (total) => `共有${total}条数据`,
        onChange: (current, pageSize) => {
            tableProps.value.pagination.current = current;
            tableProps.value.pagination.pageSize = pageSize;
            init();
        }
    },
    rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
            state.selectedRows = selectedRows;
            state.selectedRowKeys = selectedRowKeys;
        }
    },
})



const state = reactive({
    selectedRows: [],  // 选中的行
    selectedRowKeys: [], // 选中的行key
    processVisible: false,
    processForm: {
        id: '',
        opinion: ''
    },
    searchData: {
        likeVehiclePlateLicense: '',
        alarmCode:null,
        date: []
    },
    detailVisible: false,
    detailData: {}
})

// 获取报警等级颜色
const getAlarmLevelColor = (level) => {
    const colorMap = {
        'URGENT': 'red',
        'IMPORTANT': 'red',
        'GENERAL': 'orange',
        'INFO': 'gold'
    }
    return colorMap[level] || 'default'
}


onMounted(() => {
    init();
})

// 查看详情
const viewDetail = (record) => {
    bizEventDetail({id:record.id}).then(res => {
        console.log(res);
        state.detailData = res.result;
        state.detailVisible = true;
    })
}

// 处理报警
const handleAlarm = (record) => {
    state.processForm.id = record.id;
    state.processForm.opinion = '';
    state.processVisible = true;
}

// 确认处理
const confirmProcess = () => {

    if (!state.processForm.opinion.trim()) {
        message.error('请输入处理意见');
        return;
    }
    
    // 模拟处理逻辑
    const index = tableProps.value.dataSource.findIndex(item => item.id === state.processForm.id);
    if (index !== -1) {
        tableProps.value.dataSource[index].processStatus = '已处理';
        tableProps.value.dataSource[index].processOpinion = state.processForm.opinion;
        tableProps.value.dataSource[index].processor = '当前用户';
        tableProps.value.dataSource[index].processTime = dayjs().format('YYYY/MM/DD HH:mm:ss');
        tableProps.value.dataSource[index].processorUnit = '当前单位';
    }
    
    message.success('处理成功');
    state.processVisible = false;
}

// 取消处理
const cancelProcess = () => {
    state.processVisible = false;
}

// 删除报警
const deleteAlarm = (record) => {
    deleteConfirmModal(
        {fn:()=>{
            bizEventDelete({id:record.id}).then(res => {
                message.success(`删除成功`);
                init();
            })
        }}
    )
}

// 批量导出
const handleBatchExport = () => {
    if (state.selectedRowKeys.length === 0) {
        message.warning('请选择要导出的数据');
        return;
    }
    bizEventExportByIdList({
        idList: state.selectedRowKeys
    }).then(res => {
        console.log(res, 'res');
        // 下载
        downloadExcelByBlob(res, '原始事件.xls')
    })
    message.success(`导出${state.selectedRowKeys.length}条数据`);
}

//获取列表数据
const init = () => {

    bizEventQueryPage({
        pageNum: tableProps.value.pagination.current,
        pageSize: tableProps.value.pagination.pageSize,
        ...state.searchData,
        startCreateTime: state.searchData.date[0] ? state.searchData.date[0] + ' 00:00:00' : '',
        endCreateTime: state.searchData.date[1] ? state.searchData.date[1] + ' 23:59:59' : ''
    }).then(res => {
        // console.log(res);
        if (res && res.status === "000_0000_0000") {
            tableProps.value.dataSource = res.result.list
            tableProps.value.pagination.total = Number(res.result.total)
        } else {
            tableProps.value.dataSource = []
            tableProps.value.pagination.total = 0
            message.warning('暂无数据')
        }
    })
    // // 模拟API调用
    // setTimeout(() => {
    //     tableProps.value.dataSource = mockData;
    //     tableProps.value.pagination.total = 6720; // 模拟总数据量
    // }, 500);
}

//搜索
const handleSearch = () => {
    tableProps.value.pagination.current = 1;
    init()
}

//重置
const handleEmpty = () => {
    state.searchData = {
        likeVehiclePlateLicense: '',
        alarmCode:null,
        date: []
    }
    tableProps.value.pagination.current = 1;
    init()
}

const changeDate = () => {
    // 日期变化处理
}

// 格式化日期时间
const formatDateTime = (timestamp) => {
    if (!timestamp) return '';
    return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
}

// 关闭详情弹窗
const closeDetail = () => {
    state.detailVisible = false;
    state.detailData = {};
}

</script>

<style lang="less" scoped>
.user_main {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.safelist-table-container {
    height: calc(100% - 48px);
    overflow: hidden;

    .action_box {
        display: flex;
        font-size: 14px;
        color: #00CCCC;

        span {
            cursor: pointer;
            margin-right: 8px;
        }

        .process_btn {
            color: #006EFF;
            font-weight: 500;
        }

        .delete_btn {
            color: rgba(255, 47, 0, 1);
        }
    }
}

.detail-content {
    .ant-descriptions-item-label {
        font-weight: 500;
        background-color: #fafafa;
    }
}

.mb-16 {
    margin-bottom: 16px;
}

.mr-8 {
    margin-right: 8px;
}
</style> 